namespace EyeOpen.Trial.Data
{
	using System;
	using System.Collections;
	using System.Collections.Generic;
	using System.Data;
	using System.Data.Entity;
	using System.Linq;
	using System.Linq.Expressions;

	internal class Repository<T>
		: IRepository<T>
		where T : class
	{
		private readonly DbContext dbContext;

		private readonly DbSet<T> dbSet;
		private readonly IQueryable<T> queryable;

		public Repository(DbContext dbContext, DbSet<T> dbSet)
		{
			this.dbContext = dbContext;
			this.dbSet = dbSet;
			this.queryable = dbSet.AsQueryable();
		}

		public Expression Expression
		{
			get
			{
				return queryable.Expression;
			}
		}

		public Type ElementType
		{
			get
			{
				return queryable.ElementType;
			}
		}

		public IQueryProvider Provider
		{
			get
			{
				return queryable.Provider;
			}
		}

		public void Add(T entity)
		{
			dbSet.Add(entity);
		}

		public void Update(T entity)
		{
			dbSet.Attach(entity);
			dbContext.Entry(entity).State = EntityState.Modified;
		}

		public void Remove(T entity)
		{
			dbSet.Remove(entity);
		}

		public IEnumerator<T> GetEnumerator()
		{
			return queryable.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
}